package com.example.chamberlainserver.security;

import com.example.chamberlainserver.Entry.User;
import com.example.chamberlainserver.Service.UserLogService;
import com.example.chamberlainserver.Service.UserService;
import com.example.chamberlainserver.mapper.UserLoginLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.session.SessionDestroyedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户登出事件监听器
 * 监听会话销毁事件，记录用户登出日志
 */
@Component
public class LogoutEventListener {

    private final UserLogService userLogService;
    
    @Autowired
    private UserLoginLogMapper loginLogMapper;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    public LogoutEventListener(UserLogService userLogService) {
        this.userLogService = userLogService;
    }
    
    /**
     * 监听会话销毁事件，记录用户登出日志
     * 当用户登出或会话超时时，会触发此事件
     */
    @EventListener
    public void handleSessionDestroyedEvent(SessionDestroyedEvent event) {
        List<SecurityContext> securityContexts = event.getSecurityContexts();
        
        for (SecurityContext securityContext : securityContexts) {
            Authentication authentication = securityContext.getAuthentication();
            if (authentication != null && authentication.isAuthenticated()) {
                String username = authentication.getName();
                
                try {
                    // 获取最近的登录日志ID
                    Long loginLogId = loginLogMapper.getLatestLoginLogIdByUsername(username);
                    if (loginLogId != null) {
                        // 记录用户登出日志
                        userLogService.recordUserLogout(loginLogId);
                        
                        // 获取用户信息
                        User user = userService.getUserByStuNo(username);
                        if (user != null) {
                            // 获取用户角色
                            String userRole = "";
                            for (var authority : authentication.getAuthorities()) {
                                userRole += authority.getAuthority() + ",";
                            }
                            if (userRole.endsWith(",")) {
                                userRole = userRole.substring(0, userRole.length() - 1);
                            }
                            
                            // 记录用户操作日志
                            userLogService.recordUserAction(
                                user.getId(), // 用户ID
                                username,
                                userRole,
                                "用户管理", // 模块
                                "会话超时退出", // 操作类型
                                "用户会话超时或被销毁", // 描述
                                "SESSION", // 请求方法
                                "/session/destroyed", // 请求URL
                                "0.0.0.0", // 请求IP
                                "", // 请求参数
                                true, // 操作状态
                                "", // 错误消息
                                0L // 执行时长
                            );
                        }
                    }
                } catch (Exception e) {
                    // 记录异常但不影响登出流程
                    System.err.println("记录登出日志时发生异常: " + e.getMessage());
                    e.printStackTrace();
                    System.err.println("用户名: " + username + ", 认证信息: " + authentication);
                }
            }
        }
    }
}